package com.fa.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.fa.ojcodesandbox.model.ExecuteCodeRequest;
import com.fa.ojcodesandbox.model.ExecuteCodeResponse;
import com.fa.ojcodesandbox.model.ExecuteMessage;
import com.fa.ojcodesandbox.model.JudgeInfo;
import com.fa.ojcodesandbox.utils.ProcessUtils;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: JavaNativeCodeSandbox
 * Package: com.fa.ojcodesandbox
 * Description:
 *
 * @Author:
 * @Create: 2024/4/27 - 10:28
 * @Version: v1.0
 */
@Slf4j
public class JavaDockerCodeSandboxOld implements CodeSandbox{

    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";


    //设置超时时间，防止用户恶意长时间占用资源
    private static final long TIME_OUT = 100000;

    //定义一个黑名单，用于限制用户的操作
    private static final List<String> BLACK_LIST = Arrays.asList("Files","exec","rm", "rm -rf", "rm -r", "rm -R", "rm -d", "rm -D");

    // wordTree用于校验代码中是否含有敏感字符
    private static final WordTree WORD_TREE;

    // 首次初始化，是否需要下载镜像
    private static Boolean FIRST_INIT = true;

    static {
        // 初始化字典树
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(BLACK_LIST);
    }

    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaNativeCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        String code = ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println("executeCodeResponse = " + executeCodeResponse);
    }

    /**
     * 1. 把用户的代码保存为.java文件
     * 2. 将 .java文件编译为 .class文件
     * 3. 把编译好的文件上传到docker容器环境内（使用docker的容器数据卷）
     * 4. 在容器中执行代码，得到输出结果
     * 5. 收集整理输出结果
     * 6. 文件清理
     * 7. 程序结束关闭容器
     * 8. 错误处理，提升程序的健壮性
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 校验用户传入的代码，是否包含敏感词汇
        /* 优化：将这两行代码放到静态代码块中，当类加载是只需要创建一次
        WordTree wordTree = new WordTree();
        wordTree.addWords(BLACK_LIST);*/
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null && foundWord.length() > 0) {
            System.out.println("foundWord = " + foundWord);
            //foundWord，找的单词长度大于0 说明代码中存在黑名单中的单词
            return getErrorResponse("代码中包含敏感词汇");
        }

        // 这里得到的是项目的 全路径
        String userDir = System.getProperty("user.dir");
        // 这里使用 File.separator 作为分隔符而不用 /，是为了兼容 Linux、mac
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，不存在则创建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 1.把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodeFileFullPath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodeFileFullPath, StandardCharsets.UTF_8);
        // 2. 编译.java文件， 得到.class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage compileExecuteMessage = ProcessUtils.getRunProcessResult(compileProcess, "编译");
            System.out.println("compileExecuteMessage = " + compileExecuteMessage);
        } catch (IOException e) {
            return getErrorResponse(e);
        }

        // 3. 创建容器，把文件复制到容器内执行
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        // 拉取openjdk：8镜像     这里需要指定下载镜像的版本，否则会下载所有版本
        String imageName = "cnadiminti/dynamodb-local:latest";
        // 查看是否下载openjdk:8镜像
        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        List<Image> imageList = listImagesCmd.withShowAll(true).exec();
        for (Image image: imageList) {
            String[] imageRepoTags = image.getRepoTags();
            if (ArrayUtil.contains(imageRepoTags, imageName)) {
                // 如果 imageRepoTags包含 imageName，说明 需要的镜像已经下载，直接将 First_Init设置为false，这样就不需要重新下载镜像
                FIRST_INIT = false;
            }
        }
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    log.info("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                log.warn("拉取镜像异常");
                throw new RuntimeException(e);
            }
        }

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(imageName);
        HostConfig hostConfig = new HostConfig();
        // 这里给每个docker容器设置内存大小。从这里就可以限制内存的分配；防止用户占用内存
        hostConfig.withMemory(100 * 1024 * 1024L);
        hostConfig.withMemorySwap(0l);
        // 这里给docker容器设置cpu的核数
        hostConfig.withCpuCount(1L);
        // 这里给主机设置绑定，相当于docker的数据卷挂载，将 Linux中用户代码的父目录绑定到docker的 /app目录
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)//禁用网络，防止用户盗刷带宽
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        String containerId = createContainerResponse.getId();
        if (StrUtil.isBlank(containerId)) {
            return getErrorResponse("容器创建异常");
        }
        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 在docker容器中正真要执行的命令是：docker exec jdk8的镜像名称 java -cp /app Main 1 3
        //执行命令获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        // maxRunTime只存 程序用时最长的； 在判题服务中只要有一个值超过限制时间，就说明答案不正确
        long maxRunTime = 0;
        // maxMemory 用于存储内存的最大使用量
        final long[] maxMemory = {0};
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[] { "java", "-cp", "/app", "Main"}, inputArgsArray);
            // 创建执行命令. 执行自己生成的指令
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
//            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};

            String execId = execCreateCmdResponse.getId();
            if (StrUtil.isBlank(execId)) {
                return getErrorResponse("创建docker执行命令失败");
            }
            // 获取内存占用
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    maxMemory[0] = statistics.getMemoryStats().getMaxUsage();
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {
                }

                @Override
                public void close() throws IOException {

                }
            });
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
//                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
//                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }

                @Override
                public void onComplete() {
                    super.onComplete();

                }
            };
            try {
                stopWatch.start();
                // 在容器中运行代码时，设置等待时间，防止用户的程序超时，占用资源
                boolean awaitCompletion = dockerClient.execStartCmd(execId).exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                stopWatch.stop();

//            System.out.println("awaitCompletion = " + awaitCompletion);如果程序执行时间超过超时时间，awaitCompletion = false
                if (!awaitCompletion) {
                    // 只要程序执行完毕，就要关闭容器
                    closeContainer(dockerClient);
                    //程序超时，直接return
                    return getErrorResponse("程序执行时间超过最大等待时间");
                }
                maxRunTime = Math.max(maxRunTime, stopWatch.getLastTaskTimeMillis());
            } catch (InterruptedException e) {
                log.info("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                // 执行完毕需要关闭资源
                statsCmd.close();
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessageList.add(executeMessage);
        }

        // 只要程序执行完毕，就要关闭docker容器
        closeContainer(dockerClient);

        // 4. 收集、整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        // 定义 successOutputList 用于接收执行成功的输出
        List<String> successOutputList = new ArrayList<>();
        for (ExecuteMessage executeMessage :
                executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            // 错误信息为空，执行成功
            successOutputList.add(executeMessage.getMessage());
        }
        if (successOutputList.size() == executeMessageList.size()) {
            // 如果成功执行，执行成功的list的大小和执行消息的大小相同
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(successOutputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxRunTime);
        judgeInfo.setMemory(maxMemory[0]);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5. 文件清理
        if (FileUtil.exist(userCodeParentPath)) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println(del ? "目录删除成功" : "目录删除失败");
        }

        return executeCodeResponse;
        // 6. 错误处理，提升程序健壮性
    }


    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     * @param errorMessage
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(String errorMessage) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setMessage(errorMessage);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 程序执行完毕，关闭容器
     * @param dockerClient
     */
    private void closeContainer(DockerClient dockerClient) {
        // 停止容器，删除容器
        List<Container> containerList = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container :
                containerList) {
            String removeContainerId = container.getId().substring(0, 12);
            dockerClient.removeContainerCmd(removeContainerId).withForce(true).exec();
//                    System.out.println("container = " + container.getId());
//                    System.out.println("container.getId().substring(0, 12) = " + container.getId().substring(0, 12));
        }
    }
}
